import 'package:flutter/material.dart';

class PageviewKeepAliveBasePage extends StatefulWidget {
  const PageviewKeepAliveBasePage({super.key});

  @override
  State<PageviewKeepAliveBasePage> createState() => _PageviewKeepAliveBasePageState();
}

class _PageviewKeepAliveBasePageState extends State<PageviewKeepAliveBasePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('pageview缓存'),
      ),
      body: PageView.builder(
          itemCount: 10,
          itemBuilder: (context, index) {
            return MyContainer(num: index);
          }),
    );
  }
}

class MyContainer extends StatefulWidget {
  final int num;

  const MyContainer({super.key, required this.num});

  @override
  State<MyContainer> createState() => _MyContainerState();
}

class _MyContainerState extends State<MyContainer>
    with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    //默认数据是没有缓存的，每次滑动都会执行build
    print(widget.num);
    return Center(
      child: Text('第${widget.num}个界面'),
    );
  }

  @override
  bool get wantKeepAlive => true; //返回true表示缓存页面
}
